#!/usr/bin/env bash
#build in jenkins ，jenkins auto deploy shell
#该脚本应该放置在所部署的机器上

# docker 仓库地址
REG_URL="192.168.111.34:5000"
# 镜像名称
IMG_NAME=
# 镜像tag 默认latest
IMG_TAG="latest"
# 容器名称
CONTAINER_NAME=$IMG_NAME

while getopts "r:i:c:t:" opt
do
    case $opt in
        r)
        REG_URL=$OPTARG
        ;;
        i)
        IMG_NAME=$OPTARG
        ;;
        c)
        CONTAINER_NAME=$OPTARG
        ;;
        t)
        IMG_TAG=$OPTARG
        ;;
        ?)
        echo "${OPTARG}参数错误"
        exit 1;;
    esac
done
if [ ! "$CONTAINER_NAME" ]; then
    echo '容器名称参数不能为空!'
    exit 1
fi
if [ ! "$IMG_NAME" ]; then
    echo '镜像名称参数不能为空!'
    exit 1
fi

echo '================开始停止清理同名容器================'
#cid=$(docker ps -a | grep -w "$CONTAINER_NAME" | awk '{print $1}')
#if [ "$cid" != "" ]; then
#   docker rm -f $cid
#   sleep 3s
#fi
docker rm -f $(docker ps -a | grep -w "$CONTAINER_NAME" | awk '{print $1}')
sleep 3s
echo '================结束停止清理同名容器================'

echo '================开始清理本地镜像================'
#imageid=$(docker images |awk '{if($2=="<none>")  print $3}')
#if [ $imageid != "" ]; then
#   docker rmi $imageid
#   sleep 3s
#fi
docker rmi $(docker images |awk '{if($2=="<none>")  print $3}')
sleep 3s
echo '================结束清理本地镜像================'

echo '================开始拉取镜像================'
docker pull ${REG_URL}/${IMG_NAME}:${IMG_TAG}
echo '================拉取镜像结束================'



